<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\dbbackups\admin\controller;

use onekey\File;
use think\facade\Db;
use think\facade\View;
use app\admin\BaseController;
/**
 * 文章
 */
class Backups extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->path = plugin_path() . "dbbackups/backups/";
        if (! is_dir($this->path)) {
            mkdir($this->path, 0777, true);
        }
    }
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $data = [];
            foreach (scandir($this->path) as $key => $name) {
                if ($name !== '.' &&  $name !== '..') {
                    $var = [
                        'id'          => $name,
                        'name'        => $name, 
                        'size'        => File::formatBytes(filesize($this->path . $name)), 
                        'create_time' =>  date ("Y-m-d H:i:s" , filemtime($this->path . $name))
                    ];
                    array_unshift($data, $var);
                }
            }
            return json(['status' => 'success','message' => '获取成功', 'data' => $data]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 备份
     */
    public function back() 
    {
        if ($this->request->isPost()) {
            $name = time() .".sql";
            $to_file_name = $this->path . $name;
            //数据库中有哪些表
            $tables = Db::query('SHOW TABLES ');
            $tablelist = array();
            foreach ($tables as $v) {
                foreach ($v as $vv) {
                    $tablelist[] = $vv;
                }
            }
            $info = "-- ----------------------------\r\n";
            $info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
            $info .= "-- ----------------------------\r\n\r\n";
            file_put_contents($to_file_name,$info);
            //将每个表的表结构导出到文件
            foreach ($tablelist as $val) {
                $res = Db::query('show create table '.$val);
                foreach ($res as $v) {
                    $newres = $v['Create Table'];
                }
                $info = "-- ----------------------------\r\n";
                $info .= "-- Table structure for `".$val."`\r\n";
                $info .= "-- ----------------------------\r\n";
                $info .= "DROP TABLE IF EXISTS `".$val."`;\r\n";
                $sqlStr = $info.$newres.";\r\n\r\n";
                //追加到文件
                file_put_contents($to_file_name,$sqlStr,FILE_APPEND);
            }
            //将每个表的数据导出到文件
            foreach ($tablelist as $val) {
                $sql = "select * from ".$val;
                $res = Db::query('select * from '.$val);
                //如果表中没有数据，则继续下一张表
                if(count($res)<1) continue;
                $info = "-- ----------------------------\r\n";
                $info .= "-- Records for `".$val."`\r\n";
                $info .= "-- ----------------------------\r\n";
                file_put_contents($to_file_name,$info,FILE_APPEND);
                //读取数据
                foreach ($res as $v) {
                    $sqlstr = "INSERT INTO `".$val."` VALUES (";
                    foreach ($v as $vv) {
                        //将数据中的单引号转义，否则还原时会出错
                        $newvv = str_replace("'","\'",$vv);
                        $sqlstr .= "'".$newvv."', ";
                    }
                    //去掉最后一个逗号和空格
                    $sqlstr = substr($sqlstr,0,strlen($sqlstr)-2);
                    $sqlstr .= ");\r\n";
                    file_put_contents($to_file_name,$sqlstr,FILE_APPEND);
                }
                file_put_contents($to_file_name,"\r\n",FILE_APPEND);
            }
            return json(['status' => 'success', 'message' => '新增成功']);
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            foreach ($input['ids'] as $key => $name) {
                if (is_file($this->path . $name)) {
                    unlink($this->path . $name);
                }
            }
            return json(['status' => 'success', 'message' => '删除成功']);
        }
    }

    /**
     * 下载
     */
    public function download()
    {
        $input = input();
        $file  = $this->path . $input['name'];
        return download($file, $input['name']);
    }
}